package cn.edu.ctbu.aop.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

@Aspect
@Component
@Slf4j
public class HttpAspect {
    @Pointcut("execution(public * cn.edu.ctbu.aop.restcontroller.StudentRestController.*(..))")
    public void log() {}
    /**
     * 记录进入方法的信息
     * @param joinPoint
     */
    @Before("log()")
    public void doBefore(JoinPoint joinPoint) {
        String enterMessage = String.format("进入方法: %s with arguments: %s", joinPoint.getSignature(), joinPoint.getArgs());
        // 打印到控制台
        System.out.println(enterMessage);
        // 记录到日志
        log.info(enterMessage);
    }
    /**
     * 记录方法结束的信息
     * @param joinPoint
     */
    @After("log()")
    public void doAfter(JoinPoint joinPoint) {
        String exitMessage = String.format("退出方法: %s", joinPoint.getSignature());
        // 打印到控制台
        System.out.println(exitMessage);
        // 记录到日志
        log.info(exitMessage);
    }
    /**
     * 记录方法返回值的信息
     * @param object
     */
    @AfterReturning(returning = "object", pointcut = "log()")
    public void doAfterReturning(Object object) {
        String returnMessage = String.format("方法返回: %s", object);
        // 打印到控制台
        System.out.println(returnMessage);
        // 记录到日志
        log.info(returnMessage);
    }
    /**
     * 记录方法抛出的异常信息
     * @param joinPoint
     * @param exception
     */
    @AfterThrowing(pointcut = "log()", throwing = "exception")
    public void doAfterThrowing(JoinPoint joinPoint, Throwable exception) {
        String exceptionMessage = String.format("方法抛出异常: %s with message: %s", joinPoint.getSignature(), exception.getMessage());
        // 打印到控制台
        System.out.println(exceptionMessage);
        // 记录到日志
        log.error(exceptionMessage);
    }
}
